import 'package:flutter/material.dart';
import 'package:metaera_flutter/utils/Device.dart';
import 'package:metaera_flutter/widgets/CategoryItem.dart';
import 'package:metaera_flutter/widgets/Toasts.dart';
import 'package:metaera_flutter/services/umeng_analytics.dart';
import 'package:metaera_flutter/widgets/ArticleItem.dart';
import 'package:metaera_flutter/widgets/Banner.dart';
import 'package:metaera_flutter/widgets/RegionItem.dart';
import 'package:metaera_flutter/utils/Color.dart';
import 'package:metaera_flutter/net/request.dart';
import 'package:metaera_flutter/models/ArticleModel.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // 首页整体数据
  late Map homeData;

  // 分类Tab选中index
  int _selectedTabIndex = 0;

  // 分类Tab
  late List<Map> _tabTitles;

  // 资讯列表（为每个分类维护独立的列表）
  final Map<int, List<ArticleModel>> _articleLists = {};

  // 分页信息（为每个分类维护独立的分页信息）
  final Map<int, int> _pagesMap = {};
  final Map<int, bool> _hasMoreMap = {};
  final Map<int, bool> _loadingMap = {};

  // 广告列表
  late List<Map> bnnerLists;

  // 添加 PageController 支持滑动切换
  late PageController _pageController;

  // 为每个分类维护独立的滚动控制器
  final Map<int, ScrollController> _scrollControllers = {};

  int size = 25;

  @override
  void initState() {
    super.initState();
    _tabTitles = [];
    bnnerLists = [];
    _pageController = PageController(initialPage: _selectedTabIndex);
    homeLinsts();
    getRecommendBanner();
    UmengAnalytics.onPageStart('HomePage');
  }

  // 获取首页数据
  void homeLinsts() async {
    try {
      final result = await Request().homeLinsts();
      if (result['code'] != 200) {
        Toasts.error("获取首页数据失败，请刷新");
        return;
      } else {
        _selectedTabIndex = 0;
        homeData = result['data'] as Map;
        setState(() {
          _tabTitles = List<Map>.from(homeData['categoryLists'] as List);
          _tabTitles.insert(0, {'id': 0, 'name': '全部'});
        });
        getArticleList(_selectedTabIndex);
      }
    } catch (e) {
      Toasts.error("获取首页数据失败，请刷新");
    }
  }

  // 获取顶部banner
  void getRecommendBanner() async {
    try {
      final result = await Request().getRecommendBanner({"type": 1});
      if (result['code'] != 200) {
        Toasts.error("获取顶部banner数据失败，请刷新");
        return;
      } else {
        homeData = result['data'] as Map;
        setState(() {
          bnnerLists = List<Map>.from(homeData['list'] as List);
        });
      }
    } catch (e) {
      Toasts.error("获取顶部banner数据失败，请刷新");
    }
  }

  // 获取新闻列表
  void getArticleList(int categoryIndex) async {
    try {
      if (_tabTitles.isEmpty) {
        return;
      }
      // 事件统计
      UmengAnalytics.onEvent(
        'click_button',
        properties: {'button_name': 'login', 'user_type': 'vip'},
      );
      // 初始化分类数据
      if (!_articleLists.containsKey(categoryIndex)) {
        _articleLists[categoryIndex] = [];
        _pagesMap[categoryIndex] = 1;
        _hasMoreMap[categoryIndex] = true;
        _loadingMap[categoryIndex] = false;
      }

      // 如果正在加载，直接返回
      if (_loadingMap[categoryIndex]!) {
        return;
      }

      setState(() {
        _loadingMap[categoryIndex] = true;
      });

      late Map<String, dynamic> par = {};
      par['category_id'] = _tabTitles[categoryIndex]['id'];
      par['page'] = _pagesMap[categoryIndex];
      par['size'] = size;
      par['type'] = 1;
      if (par['category_id'] == 0) {
        par['type1'] = 7;
      }

      final result = await Request().getArticleList(par);
      if (result['code'] != 200) {
        Toasts.error("获取新闻列表失败，请刷新");
        return;
      } else {
        setState(() {
          // 如果是第一页，替换数据；否则追加数据
          if (_pagesMap[categoryIndex] == 1) {
            _articleLists[categoryIndex] = List<ArticleModel>.from(
              (result['data']['list'] as List).map(
                (item) => ArticleModel.fromJson(item as Map<String, dynamic>),
              ),
            );
          } else {
            _articleLists[categoryIndex]!.addAll(
              List<ArticleModel>.from(
                (result['data']['list'] as List).map(
                  (item) => ArticleModel.fromJson(item as Map<String, dynamic>),
                ),
              ),
            );
          }

          // 更新是否有更多数据
          _hasMoreMap[categoryIndex] =
              (result['data']['list'] as List).length >= size;
        });
      }
    } catch (e) {
      print('Error loading home lists: $e');
    } finally {
      setState(() {
        _loadingMap[categoryIndex] = false;
      });
    }
  }

  // 加载更多数据
  void _loadMoreData(int categoryIndex) async {
    if (!_loadingMap[categoryIndex]! && _hasMoreMap[categoryIndex]!) {
      setState(() {
        _pagesMap[categoryIndex] = _pagesMap[categoryIndex]! + 1;
      });
      getArticleList(categoryIndex);
    }
  }

  // 下拉刷新
  Future<void> _refreshData(int categoryIndex) async {
    setState(() {
      _pagesMap[categoryIndex] = 1;
      _hasMoreMap[categoryIndex] = true;
    });
    getArticleList(categoryIndex);
  }

  // 根据分类加载新闻
  void _loadNewsByCategory(int categoryIndex) {
    setState(() {
      _selectedTabIndex = categoryIndex;
    });

    // 如果该分类还没有数据，加载数据
    if (!_articleLists.containsKey(categoryIndex) ||
        _articleLists[categoryIndex]!.isEmpty) {
      getArticleList(categoryIndex);
    }
  }

  // 获取或创建滚动控制器
  ScrollController _getScrollController(int categoryIndex) {
    if (!_scrollControllers.containsKey(categoryIndex)) {
      ScrollController controller = ScrollController();
      controller.addListener(() {
        // 检查是否滚动到底部
        if (controller.position.pixels >=
            controller.position.maxScrollExtent - 200) {
          _loadMoreData(categoryIndex);
        }
      });
      _scrollControllers[categoryIndex] = controller;
    }
    return _scrollControllers[categoryIndex]!;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 分类Tab - 固定在顶部
        Container(
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(color: Color(0xFFEEEEEE), width: 1),
            ),
          ),
          child: SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            physics: AlwaysScrollableScrollPhysics(),
            padding: EdgeInsets.symmetric(horizontal: 8),
            child: Row(
              children: _tabTitles.asMap().entries.map((entry) {
                int index = entry.key;
                String title = entry.value['name'] as String;
                return CategoryItem(
                  index: index,
                  title: title,
                  currentIndex: _selectedTabIndex,
                  pageController: _pageController,
                );
              }).toList(),
            ),
          ),
        ),

        // 主要内容区域 - 使用 PageView 支持滑动切换
        Expanded(
          child: PageView(
            controller: _pageController,
            onPageChanged: (index) {
              _loadNewsByCategory(index);
            },
            children: List.generate(_tabTitles.length, (index) {
              return _buildCategoryContent(index);
            }),
          ),
        ),
      ],
    );
  }

  // 为每个分类构建内容
  Widget _buildCategoryContent(int categoryIndex) {
    // 确保该分类的数据结构已初始化
    if (!_articleLists.containsKey(categoryIndex)) {
      _articleLists[categoryIndex] = [];
      _pagesMap[categoryIndex] = 1;
      _hasMoreMap[categoryIndex] = true;
      _loadingMap[categoryIndex] = false;
    }

    return RefreshIndicator(
      onRefresh: () => _refreshData(categoryIndex),
      child: ListView(
        controller: _getScrollController(categoryIndex), // 使用独立的滚动控制器
        children: [
          // 仅在"全部"分类显示轮播Banner和区域选择器
          if (categoryIndex == 0) ...[
            Container(
              color: AppColors.colorF7F7F7,
              child: Column(
                children: [
                  BannerSlider(images: bnnerLists),
                  RegionItem(),
                ],
              ),
            ),
          ],

          // 新闻列表
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.vertical(top: Radius.circular(10)),
            ),
            padding: EdgeInsets.only(top: DeviceUtils.width10),
            child: ListView.builder(
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              itemCount:
                  _articleLists[categoryIndex]!.length +
                  (_hasMoreMap[categoryIndex]! ? 1 : 0), // 添加加载指示器
              itemBuilder: (context, index) {
                // 如果是最后一个item且还有更多数据，显示加载指示器
                if (index == _articleLists[categoryIndex]!.length) {
                  return _buildLoadMoreIndicator(categoryIndex);
                }
                return ArticleItem(
                  articleModel: _articleLists[categoryIndex]![index],
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  // 构建加载更多指示器
  Widget _buildLoadMoreIndicator(int categoryIndex) {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(
            width: 20,
            height: 20,
            child: CircularProgressIndicator(
              strokeWidth: 2.0,
              valueColor: AlwaysStoppedAnimation<Color>(AppColors.color6184DD),
            ),
          ),
          SizedBox(width: 10),
          Text(
            '正在加载更多...',
            style: TextStyle(color: AppColors.color9C9C9C, fontSize: 14),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _pageController.dispose();
    // 释放所有滚动控制器
    _scrollControllers.values.forEach((controller) => controller.dispose());
    UmengAnalytics.onPageEnd('HomePage');
    super.dispose();
  }
}
